import { useMenuStore } from "@/stores/menu";
import { useSettingsStore } from "@/stores/settings";
import { useTagsStore } from "@/stores/tags";
import { useUserStore } from "@/stores/user";
import { ElNotification } from "element-plus";
import { createRouter, createWebHistory, createWebHashHistory } from "vue-router";

const WHITE_LIST = ["/login", "/register"];

const HistoryMode = {
    history: createWebHistory,
    hash: createWebHashHistory,
};

const router = createRouter({
    history: HistoryMode[import.meta.env.VITE_HISTORY_MODE](import.meta.env.BASE_URL),
    routes: [
        {
            path: "/",
            name: "layout",
            component: () => import("@/layouts/index.vue"),
            children: [
                {
                    path: "/403",
                    component: () => import("@/views/403.vue"),
                },
                {
                    path: "/404",
                    component: () => import("@/views/404.vue"),
                },
            ],
        },
        {
            name: "user",
            path: "/user",
            component: () => import("@/layouts/user.vue"),
            children: [
                {
                    name: "login",
                    path: "/login",
                    component: () => import("@/views/user/login.vue"),
                },
            ],
        },
        {
            path: "/:path(.*)",
            name: "not found",
            redirect: "/404",
        },
    ],
});

router.beforeEach(async (to, from) => {
    const user = useUserStore();
    const menu = useMenuStore();
    const tags = useTagsStore();
    const settings = useSettingsStore();

    const loginUrl = `/login?redirect=${to.fullPath}`;

    console.log("router.beforeEach", to, from, router.getRoutes());
    if (WHITE_LIST.includes(to.path)) return;

    if (!user.token) return loginUrl;

    if (!menu.inited) {
        const res = await user.getUserInfo();
        if (!res) return loginUrl;

        await menu.init();
        return { path: (to.redirectedFrom || to).fullPath, replace: true };
    }

    // 检查页面权限
    if (settings.auth && menu.routeNames.includes(to.name as string) && !user.urls.includes(to.path)) {
        ElNotification({ title: "错误", message: "没有访问权限", type: "error" });
        return false;
    }

    if (to.meta.link) return false;

    const title = [settings.title];

    if (to.meta.title) {
        title.unshift(to.meta.title);
    } else {
        if (to.meta && to.meta.breadcrumb && to.meta.breadcrumb.length) {
            const parent = to.meta.breadcrumb[to.meta.breadcrumb.length - 1];
            if (parent) {
                title.unshift(parent.meta.title);
            }
        }
    }

    document.title = title.join(" - ");

    tags.addViewTag(to);
});

router.onError((error) => {
    console.log("router catch error.", error);
});

(window as any).router = router;

export default router;
